// ignore_for_file: prefer_const_constructors

import 'dart:io';

import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:get_storage/get_storage.dart';
import 'package:multi_shop/models/user.dart';
import 'package:multi_shop/utils/index.dart';
import 'package:multi_shop/widgets/change_password_dialog.dart';
import '../../services/user_api.dart';
import 'package:image_picker/image_picker.dart';

/// 个人信息页面
class ProfilePage extends StatefulWidget {
  const ProfilePage({Key? key}) : super(key: key);

  @override
  State<ProfilePage> createState() => _ProfilePageState();
}

class _ProfilePageState extends State<ProfilePage> with WidgetsBindingObserver {
  final api = UserApi();
  final box = GetStorage();

  UserInfo? userInfo;

  @override
  void initState() {
    super.initState();
    // 读取本地
    userInfo = box.read('userInfo');
    // 如需启动时强制拉取最新，可取消注释：
    _reloadFromServer();
  }

  Future<void> _reloadFromServer() async {
    try {
      final fresh = await api.getUserInfo(); // 确保你的 UserApi 有这个方法
      userInfo = fresh;
      await box.write('userInfo', fresh);
      if (mounted) setState(() {});
    } catch (e) {
      // 可选：提示失败
    }
  }

  // 通用：弹出输入框并返回新值
  Future<String?> _editText({
    required String title,
    required String initial,
    String? hint,
    String? Function(String value)? validator,
    TextInputType keyboardType = TextInputType.text,
  }) async {
    final ctrl = TextEditingController(text: initial);
    String? error;
    return await Get.dialog<String>(
      AlertDialog(
        title: Text(title),
        content: Column(
          mainAxisSize: MainAxisSize.min,
          children: [
            TextField(
              controller: ctrl,
              keyboardType: keyboardType,
              decoration: InputDecoration(hintText: hint, errorText: error),
              onChanged: (_) {
                if (error != null) {
                  // 轻微交互：实时清错误
                  error = null;
                }
              },
            ),
          ],
        ),
        actions: [
          TextButton(onPressed: () => Get.back(), child: Text('取消')),
          TextButton(
            onPressed: () {
              final v = ctrl.text.trim();
              if (validator != null) {
                final msg = validator(v);
                if (msg != null) {
                  // 使用临时 setState 不太方便，这里简单用 snackbar 提示
                  Get.snackbar('提示', msg, snackPosition: SnackPosition.BOTTOM);
                  return;
                }
              }
              Get.back(result: v);
            },
            child: Text('保存'),
          ),
        ],
      ),
      barrierDismissible: false,
    );
  }

  // 选择性别
  Future<int?> _pickGender(int current) async {
    int value = current;
    return await Get.dialog<int>(
      AlertDialog(
        title: Text('选择性别'),
        content: StatefulBuilder(
          builder: (_, setSt) => Column(
            mainAxisSize: MainAxisSize.min,
            children: [
              RadioListTile<int>(
                title: Text('男'),
                value: 1,
                groupValue: value,
                onChanged: (v) => setSt(() => value = v ?? 1),
              ),
              RadioListTile<int>(
                title: Text('女'),
                value: 2,
                groupValue: value,
                onChanged: (v) => setSt(() => value = v ?? 2),
              ),
              RadioListTile<int>(
                title: Text('保密'),
                value: 0,
                groupValue: value,
                onChanged: (v) => setSt(() => value = v ?? 0),
              ),
            ],
          ),
        ),
        actions: [
          TextButton(onPressed: () => Get.back(), child: Text('取消')),
          TextButton(
            onPressed: () => Get.back(result: value),
            child: Text('确定'),
          ),
        ],
      ),
      barrierDismissible: false,
    );
  }

  Future<void> _applyFullUpdate(Map<String, dynamic> changed) async {
    if (userInfo == null || changed.isEmpty) return;

    // 合并出最新的完整对象
    final merged = {...userInfo!.toJson(), ...changed};
    final updated = UserInfo.fromJson(merged);

    try {
      Get.dialog(
        const Center(child: CircularProgressIndicator()),
        barrierDismissible: false,
      );
      await api.updateUserInfo(updated); // ← 发送整对象
      await box.write('userInfo', updated); // 本地保存
      userInfo = updated;
      if (mounted) setState(() {});
      Get.back();
      Get.snackbar('成功', '资料已更新', snackPosition: SnackPosition.TOP);
    } catch (e) {
      Get.back();
      Get.snackbar('更新失败', e.toString(), snackPosition: SnackPosition.TOP);
    }
  }

  // ——各字段编辑入口——

  Future<void> _editGender() async {
    final old = userInfo?.gender;
    final v = await _pickGender(old!);
    if (v != null && v != old) {
      await _applyFullUpdate({'gender': v});
    }
  }

  Future<void> _editPayPwd() async {
    await ChangePasswordDialog.show(
      context,
      mode: PasswordMode.pay,
      requireOld: userInfo!.hasPayPwd,
      onConfirm: ({required String oldPwd, required String newPwd}) async {
        final oldPwdSign = hmacSha256Hex(key: oldPwd, message: oldPwd);
        final newPwdSign = hmacSha256Hex(key: newPwd, message: newPwd);
        await api.updatePassword(
          oldPwd: oldPwdSign,
          newPwd: newPwdSign,
          type: 1,
        );
        await api.getUserInfo();
        userInfo = box.read('userInfo');
      },
    );
  }

  Future<void> _editLoginPwd() async {
    await ChangePasswordDialog.show(
      context,
      mode: PasswordMode.login,
      requireOld: userInfo!.hasLoginPwd,
      onConfirm: ({required String oldPwd, required String newPwd}) async {
        final oldPwdSign = hmacSha256Hex(key: oldPwd, message: oldPwd);
        final newPwdSign = hmacSha256Hex(key: newPwd, message: newPwd);
        await api.updatePassword(
          oldPwd: oldPwdSign,
          newPwd: newPwdSign,
          type: 2,
        );
        await api.getUserInfo();
        userInfo = box.read('userInfo');
      },
    );
  }

  // 点击头像：底部选择拍照或相册
  void _showAvatarPickerSheet() {
    showModalBottomSheet(
      context: context,
      builder: (_) => SafeArea(
        child: Column(
          mainAxisSize: MainAxisSize.min,
          children: [
            ListTile(
              leading: const Icon(Icons.photo_library),
              title: const Text('从相册选择'),
              onTap: () {
                Navigator.pop(context);
                _pickAndUpload(ImageSource.gallery);
              },
            ),
            ListTile(
              leading: const Icon(Icons.photo_camera),
              title: const Text('拍照'),
              onTap: () {
                Navigator.pop(context);
                _pickAndUpload(ImageSource.camera);
              },
            ),
            const SizedBox(height: 4),
          ],
        ),
      ),
    );
  }

  // 选择并上传
  Future<void> _pickAndUpload(ImageSource source) async {
    try {
      final picker = ImagePicker();
      final XFile? x = await picker.pickImage(
        source: source,
        maxWidth: 1024, // 简单压缩，减小上传体积
        imageQuality: 85,
      );
      if (x == null) return;

      // 显示加载
      Get.dialog(
        const Center(child: CircularProgressIndicator()),
        barrierDismissible: false,
      );

      // // 上传，拿到URL（下面给出 UserApi.uploadAvatar 示例）
      // final url = await api.uploadFile(File(x.path));
      var url = "";
      if (kIsWeb) {
        final bytes = await x.readAsBytes(); // Uint8List
        url = await api.uploadFileBytes(bytes, x.name); // 用字节上传
      } else {
        url = await api.uploadFile(File(x.path)); // 移动端用 File
      }

      // 全量更新：把 avatar 改成新地址
      final merged = {...userInfo!.toJson(), 'avatar': url};
      final updated = UserInfo.fromJson(merged);
      await api.updateUserInfo(updated);
      await GetStorage().write('userInfo', updated);

      setState(() => userInfo = updated);
      Get.back(); // 关loading
      Get.snackbar('成功', '头像已更新', snackPosition: SnackPosition.TOP);
    } catch (e) {
      if (Get.isDialogOpen == true) Get.back();
      debugPrint(e.toString());
      Get.snackbar('失败', e.toString(), snackPosition: SnackPosition.TOP);
    }
  }

  @override
  Widget build(BuildContext context) {
    final name = userInfo?.username ?? '--';
    final email = userInfo?.email ?? '--';
    final gender = userInfo?.gender;
    return Scaffold(
      appBar: AppBar(title: Text('个人信息'), elevation: 0),
      body: SingleChildScrollView(
        child: Column(
          children: [
            // 头像与基本信息
            Container(
              color: Colors.white,
              padding: const EdgeInsets.symmetric(vertical: 24),
              child: Column(
                children: [
                  InkWell(
                    onTap: _showAvatarPickerSheet,
                    borderRadius: BorderRadius.circular(56),
                    child: Stack(
                      alignment: Alignment.bottomRight,
                      children: [
                        CircleAvatar(
                          radius: 50,
                          backgroundImage: (userInfo?.avatar.isNotEmpty == true)
                              ? NetworkImage(userInfo!.avatar) as ImageProvider
                              : const AssetImage('assets/images/avatar.jpeg'),
                        ),
                        Container(
                          padding: const EdgeInsets.all(6),
                          decoration: BoxDecoration(
                            color: Colors.black54,
                            borderRadius: BorderRadius.circular(16),
                          ),
                          child: const Icon(
                            Icons.photo_camera,
                            size: 16,
                            color: Colors.white,
                          ),
                        ),
                      ],
                    ),
                  ),
                  const SizedBox(height: 12),
                  Text(
                    name,
                    style: const TextStyle(
                      fontSize: 20,
                      fontWeight: FontWeight.bold,
                    ),
                  ),
                  const SizedBox(height: 4),
                  Text(
                    email,
                    style: TextStyle(fontSize: 14, color: Colors.grey[600]),
                  ),
                ],
              ),
            ),
            SizedBox(height: 16),

            // 信息项列表
            Card(
              margin: EdgeInsets.symmetric(horizontal: 16),
              shape: RoundedRectangleBorder(
                borderRadius: BorderRadius.circular(8),
              ),
              child: Column(
                children: [
                  _buildListTile(
                    icon: Icons.person,
                    title: '用户名',
                    subtitle: name,
                    showTrailing: false,
                  ),
                  Divider(height: 1),
                  _buildListTile(
                    icon: Icons.email,
                    title: '邮箱',
                    subtitle: email,
                    showTrailing: false,
                  ),
                  Divider(height: 1),
                  _buildListTile(
                    icon: Icons.wc,
                    title: '性别',
                    subtitle: gender == 0
                        ? '保密'
                        : gender == 1
                        ? '男'
                        : '女',
                    onTap: _editGender,
                  ),
                  Divider(height: 1),
                  _buildListTile(
                    icon: Icons.password,
                    title: '支付密码',
                    subtitle: "******",
                    onTap: _editPayPwd,
                  ),
                  Divider(height: 1),
                  _buildListTile(
                    icon: Icons.password,
                    title: '登录密码',
                    subtitle: "******",
                    onTap: _editLoginPwd,
                  ),
                ],
              ),
            ),

            SizedBox(height: 24),

            // 退出登录
            Padding(
              padding: EdgeInsets.symmetric(horizontal: 16),
              child: SizedBox(
                width: double.infinity,
                height: 48,
                child: ElevatedButton(
                  onPressed: () {
                    box.remove('token');
                    box.remove('userInfo');
                    box.remove('refreshToken');
                    Get.offAllNamed('/login');
                  },
                  style: ElevatedButton.styleFrom(
                    shape: RoundedRectangleBorder(
                      borderRadius: BorderRadius.circular(8),
                    ),
                  ),
                  child: Text('退出登录'),
                ),
              ),
            ),
            SizedBox(height: 24),
          ],
        ),
      ),
    );
  }

  Widget _buildListTile({
    required IconData icon,
    required String title,
    required String subtitle,
    bool? showTrailing,
    VoidCallback? onTap,
  }) {
    return ListTile(
      leading: Icon(icon, color: const Color.fromARGB(255, 182, 182, 182)),
      title: Text(title),
      subtitle: Text(subtitle),
      trailing: (showTrailing ?? true) ? const Icon(Icons.chevron_right) : null,
      tileColor: const Color.fromARGB(255, 255, 253, 253),
      onTap: onTap,
    );
  }
}
